﻿using System;
using FunctionalCLR.Core;
using Zove.Runtime;
using Zove.Runtime.FunctionalCLR;
using FunctionalCLR.Shell;
using Zove.Shell.Core;

namespace Zove.Shell {
    public class ZoveShellUnaryFunctionTranslator : 
        UnaryFunctionTranslator {

        public IZoveShellContext Context
        {
            get;
            set;
        }

        public ZoveShellUnaryFunctionTranslator(
            IFunctionManager funMgr, string subject)
            : base(funMgr, subject) {
        }

        public override object Visit(IdentifierNode node) {
            RuntimeFactor factor = Context.GetFactor(node.Value);

            string name = string.Empty;
            if (factor == null) {
                name = node.Value;
            } else if (factor.ParentModel != null
                && factor.ParentModel.Solution.Name != null) {
                name = factor.ParentModel.Solution.Name 
                    + "." + factor.Name;
            }
            if (base.subject == name) {
                return "x";
            }

            if (factor.Status != RuntimeFactorStatus.Unknown) {
                return factor.Value;
            }

            throw new Exception(
                string.Format(
                "Factor {0} must be specified.", factor.Name));
        }
    }
}
